﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UIT.Controls.Data;
using UIT.Web.Controls.Data;
using System.Xml;
using UIT.Web.Controls.Html;
using UIT.Controls;
using UIT.Web.Controls.Template;

namespace UIT.Web.Renderers
{
    public class RepeaterRenderer : WebControlRenderer<Repeater>, IWebRenderer
    {
        public override void Render(Repeater control)
        {
            if (control.ShouldRenderOnClient(control.ItemTemplate))
            {
                if (string.IsNullOrEmpty(control.Id))
                    throw new ArgumentNullException("Id", "The id cannot be null when a control is meant to be used on a client side");
                IClientDataProvider clientDataProvider = control.DataSource as IClientDataProvider;


                StringBuilder sb = new StringBuilder();
                using (XmlWriter writer = XmlWriter.Create(sb, this.writer.Settings))
                {
                    var manager = new WebRendererManager(writer);
                    IControl emptyInstance = control.ItemTemplate.Template.CreateInstance();
                    IWebRenderer itemTemplateRenderer = (IWebRenderer)manager.Manager.Control.GetRenderer(emptyInstance);
                    itemTemplateRenderer.RunAt = RunAtMode.Client;

                    itemTemplateRenderer.Render(emptyInstance);
                    writer.Flush();
                    if (clientDataProvider == null)
                    {
                        //should fall in that case only for EnumerableDataProvider
                        ScriptManager.RegisterCall("repeater"+control.Id, JQueryControlToolkit.JQuery.Tmpl(sb.ToString(), control.DataSource.Select(new SelectArgument())).AppendTo("#" + control.Id));
                    }
                    else
                        ScriptManager.RegisterCall("repeater" + control.Id, JQueryControlToolkit.JQuery.Tmpl(sb.ToString(), clientDataProvider.Render()).AppendTo("#" + control.Id));
                }
                Manager.Control.GetRenderer<HtmlControl>().Render(new HtmlControl("div", false) { Id = control.Id, NeedFullClosingTag = true });
            }
            else
            {
                foreach (IControl child in control.Children)
                {
                    Manager.Render(child);
                }
            }
        }

        #region IVisitor<Repeater> Members

        public void Visit(Repeater visitable)
        {
            Render(visitable);
        }

        #endregion

        #region IWebRenderer Members

        public override void Initialize(RendererManager manager, object userObject)
        {
            base.Initialize(manager, userObject);
            writer = userObject as XmlWriter;
        }

        #endregion
    }
}
